<template lang="html">
 <div>
    <el-row class="mgb15">
    <div v-if="scriptText!=null && scriptText!=''">已有脚本：{{scriptText}}</div>
   <el-upload
     class="upload-demo"
     drag
     action="/crawler/api/upload/uploadFile"
      :on-success="handleSuccess"
      :on-remove="handleRemove"
      :before-upload="handleBeforeUpload"
      :on-exceed="handleExceed"
      :file-list="fileList"
      :limit=limitNum
     >
     <i class="el-icon-upload"></i>
     <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
     <div class="el-upload__tip" slot="tip">注意：文件大小不能超过10M</div>
   </el-upload>
    </el-row>
 <!-- 操作区----end -->

</div>
</template>

<script>
import apis from '../../apis/apis';
import vHead from '../common/Header.vue';
import vSidebar from '../common/Sidebar.vue';
import vTags from '../common/Tags.vue';
import vFooter from '../common/Footer.vue';
import bus from '../common/bus';
import vHtml from "../parse/html.vue"
export default {
    name: 'vhtml',
    data() {
        return {
            limitNum :1,
            listLoading : false,//
            pageInfo: { //分页
                currentPage: 1,
                pageSize: 5,
                pageTotal: 0
            },
            scriptid : '',
            scriptText:'',
            formSearch: { //表单查询
                name: '',
                taskId:this.$route.query.taskId
            },
            fileList: [],
            formEdit: { //表单编辑
                matchUrlId:'',
                matchUrlRegex: '',
                taskId : this.$route.query.taskId
            },
             rulesEdit:  {

            },
            labelPosition: 'right', //lable对齐方式
            labelWidth: '80px', //lable宽度
            formLabelWidth: '120px',
            multipleSelection: []
        };
    },
    components: {
              vHead, vSidebar, vTags, vFooter,vHtml
          },
    created() {
                  bus.$on('collapse', msg => {
                      this.collapse = msg;
                  })

                  // 只有在标签页列表里的页面才使用keep-alive，即关闭标签之后就不保存到内存中了。
                  bus.$on('tags', msg => {
                      let arr = [];
                      for (let i = 0, len = msg.length; i < len; i++) {
                          msg[i].name && arr.push(msg[i].name);
                      }
                      this.tagsList = arr;
                  })
       },
    computed:{

    },
    filters: {

    },
    mounted(){
        this.onSearch();
    },
    methods: {
       // 文件上传成功时的钩子
        handleSuccess(res, file, fileList) {
        console.log(file);
          this.$notify.success({
            title: '成功',
            message: `文件上传成功`
          });
          if(res.code==0){
            this.save(res.data.title);
            this.saveFileInfo (file.name,file.url);
          }
        },
      back (){
          this.$router.go(-1);
      },
        /**
         * 查询列表
         */
        onSearch(){
                var that=this;
                this.listLoading=true;
                let param_={
                  matchUrlId : this.$route.query.matchUrlId
                };
                let param = Object.assign({},param_);
                apis.plugApi.getAllMatchUrlPlug(param)
                  .then((data)=>{
                    this.listLoading=false;
                    if (data && data.data) {
                      var json = data.data.data[0];
                      if (data.data.successed) {
                        this.scriptid = json.script;
                        that.getScript();
                        that.getFileInfo ();
                      }
                      else if (json.message) {
                        this.$message({message: json.message,type: "error"});
                      }
                    }
                  })
                  .catch((err)=>{
                    this.listLoading=false;
                    this.$message({message: 'script查询异常，请重试',type: "error"});
                  });
         },
        getScript (){
                var that=this;
                this.listLoading=true;
                let param_={
                  plugId :  this.scriptid
                };
                let param = Object.assign({},param_,this.pageInfo);
                apis.plugApi.getAllMatchUrlPlugItemAttr(param)
                  .then((data)=>{
                    this.listLoading=false;
                    if (data && data.data) {
                      var json = data.data.rows;
                      console.log(data.data);
                      if (json && json.length > 0) {
                        that.scriptText = json[0].id;
                        this.tableData = json;
                        that.pageInfo.currentPage=data.data.curpage;
                        that.pageInfo.pageTotal=data.data.total;
                      } else if (json.message) {
                        this.$message({message: json.message, type: "error"});
                      }
                    }
                  })
                  .catch((err)=>{
                    this.listLoading=false;
                    alert('script查询异常，请重试');
                    this.$message({message: 'script查询异常，请重试',type: "error"});
                  });
        },
        getFileInfo (){
                        var that=this;
                        this.listLoading=true;
                        let param_={
                          plugId :  this.scriptid
                        };
                        let param = Object.assign({},param_,this.pageInfo);
                        apis.plugApi.getFileInfo(param)
                        .then((data)=>{
                          console.log(data);
                            this.listLoading=false;
                            if (data && data.data.status==200) {
                              var json = data.data.data;
                              that.fileList=json;
                            }else if (json.message) {
                                this.$message({message: json.message, type: "error"});
                            }
                          })
                          .catch((err)=>{
                            this.listLoading=false;
                            this.$message({message: 'script_File查询异常，请重试',type: "error"});
                          });
        },
        saveFileInfo (name,url){
             var that = this;
                        let param_={
                        name : name,
                        plugId :this.scriptid,
                        url :url
                        };
                     let param = Object.assign({}, param_,this.formEdit);
                                apis.plugApi.saveFileInfo(param)
                                .then((data)=>{
                                    if(data && data.data.status==200){
                                        this.dialogEdittVisible = false;
                                        return
                                    }
                                   this.$message({message: data.data.message,type: "error"});
                                })
                                .catch((err)=>{
                                    this.$message({message: '执行失败，请重试',type: "error"});
                                });
        },
        handleSave(){
            if(this.dialogType=='add'){
                this.save();
            }
            else if(this.dialogType=='edit'){
                this.update();
            }
            else{
                this.$message({message: '操作异常',type: "error"});
            }
        },
        /**
         * 保存
         */
        save(title) {
            var that = this;
            let param_={
            id : title,
            plugId :this.scriptid
            };
         let param = Object.assign({}, param_,this.formEdit);
                    console.log(param);
                    apis.plugApi.insertMatchUrlPlugItemAttr(param)
                    .then((data)=>{
                        if(data && data.data){
                            var json=data.data;
                             if(json && json.successed){
                                //this.$message({message: '执行成功',type: "success"});
                                this.dialogEdittVisible = false;
                                that.onSearch();
                                return;
                            }
                        }
                       this.$message({message: data.data.message,type: "error"});
                    })
                    .catch((err)=>{
                        this.$message({message: '执行失败，请重试',type: "error"});
                    });
        },
         /**
         * 更新
         */
        update() {
            var that = this;
            this.$refs["formEdit"].validate(valid => {
                if(valid){
                    let param = Object.assign({}, this.formEdit);
                    apis.seedApi.updateBySeedId(param)
                    .then((data)=>{
                        console.log(data);
                        if(data && data.data){
                            var json=data.data;
                             if(json.successed){
                                this.$message({message: '执行成功',type: "success"});
                                this.dialogEdittVisible = false;
                                that.onSearch();
                                return;
                            }
                        }
                       this.$message({message: '执行失败，请重试',type: "error"});
                    })
                    .catch((err)=>{
                        this.$message({message: '执行失败，请重试',type: "error"});
                    });
                }


            });
        },
         /**
         * 删除
         */
        handleDelete(index, rowData) {
            var that = this;
            var seedId=rowData.seedId;
            this.$confirm('此操作将永久删除该种子, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                    apis.seedApi.deleteBySeed({seedId : seedId})
                    .then((data)=>{
                          if(data.data.successed){
                              that.onSearch();
                          }
                        this.$common.isSuccess(data,()=>{
                              console.log("执行了");
                        });
                    })
                    .catch((err)=>{
                        debugger;
                        this.$message({message: '执行失败，请重试',type: "error"});
                    });

            }).catch(() => {
                this.$message({type: 'info',message: '已取消删除'});
            });

        },
        onReset(){
            this.$refs['formSearch'].resetFields();
        },
        /**
         * 打开编辑弹窗
         */
        handleAdd() {
            this.dialogEdittVisible = true;
            this.$nextTick(()=>{
                this.dialogType='add';
                this.formEditTitle='新增';
                this.formEditDisabled=false;
            });


        },
        /**
         * 打开编辑弹窗
         */
        handleEdit(index, rowData) {
            //var msg = "索引是:" + index + ",行内容是:" + JSON.stringify(rowData);
            //this.$message({message: msg,type: "success"});
            this.dialogEdittVisible = true;//等dom渲染完，读取data中初始值，然后再复制，这样重置的是data中初始值
            this.$nextTick(()=>{
                this.dialogType='edit';
                this.formEditTitle='编辑';
                this.formEditDisabled=false;
                this.formEdit= Object.assign({}, rowData);
                this.formEdit.gender+='';//必须转换成字符串才能回显
            });
        },
        /**
         * 打开详情页
         */
        handleDetail(index,rowData){
            this.dialogEdittVisible = true;
            this.$nextTick(()=>{
                 this.dialogType='show';
                this.formEditTitle='详情';
                this.formEditDisabled=true;
                this.formEdit= Object.assign({}, rowData) ;
                this.formEdit.gender+='';
            });

        },
        handleParse (index,rowData){
              this.$router.push ({
                    path : 'filter' ,
                    query : {
                        taskId : rowData.taskId
                    }
              })
        },
        /**
         * 关闭弹框，数据重置
         */
        closeDialog(formName){
            this.$refs[formName].resetFields();
        },
        /**
         * 分页大小切换
         */
        handleSizeChange(val) {
            this.pageInfo.pageSize = val;
            this.onSearch();
        },
        /**
         * 分页切换
         */
        handleCurrentChange(val) {
            this.pageInfo.currentPage = val;
            this.onSearch();
        },
        /**
         * 点击选择
         */
        handleSelectionChange(val) {
            this.multipleSelection = val;
            // this.$message({
            //     message: '选中的项是:' + JSON.stringify(this.multipleSelection),
            //     type: "success"
            // });
        },
        /**
         * 打开详情页
         */
        openDetail(row){
            this.$common.OpenNewPage(this,'detail',row);
        },
    /**
     * 文件列表移除文件时的钩子
    */
    handleRemove(file, fileList) {
                var that = this;
                var file_id=file.file_id;
                this.$confirm('此操作将永久删除该脚本, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                        apis.plugApi.deleteScript({file_id : file_id})
                        .then((data)=>{
                              if(data && data.data.status==200){
                                  this.$message({message: data.data.message,type: "success"});
                                  return
                              }
                        })
                        .catch((err)=>{
                            debugger;
                            this.$message({message: '执行失败，请重试',type: "error"});
                        });

                }).catch(() => {
                    this.$message({type: 'info',message: '已取消删除'});
                });
    },
    handleBeforeUpload(file){
     let size = file.size / 1024 / 1024 / 10;
          if(size > 10) {
            this.$notify.warning({
              title: '警告',
              message: '文件大小必须小于10M'
            })
            return
          }
        },
  // 文件超出个数限制时的钩子
    handleExceed(files, fileList) {
       if(fileList.length >=1) {
          this.$notify.warning({
              title: '警告',
              message: '每一个插件的脚本只有一个哦，请删除现有的脚本再上传新的脚本！'
           })
     }
    },


    }
};
</script>


<style lang="css">
</style>


